const e = require("express");
const express = require("express");
const app = express();
const http = require("http");
const path = require("path");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
/*定义监听端口，可以自定义，端口不要被占用*/
app.use(express.static(path.join(__dirname, "/public/")));

var PORT = 8082;
app.get("/", (req, res) => {
  res.sendFile(__dirname + "/chess.html");
});
/*监听端口*/
server.listen(PORT, () => {
  console.log("listening on *:8082");
});

var strMsg = "来自服务器的消息：";
/* 在线人员 */
var onLineUsers = {};
/* 在线人数 */
var onLineCounts = 0;
/* 房间 */
var onRooms = {};
/**
 *监听客户端连接
 *io是我们定义的服务端的socket
 *回调函数里面的socket是本次连接的客户端socket
 *io与socket是一对多的关系
 */
io.on("connection", (socket) => {
  /*所有的监听on，与发送emit都得写在连接里面，包括断开连接*/
  socket.on("login", function (obj) {
    // 登录
    let user = {
      userId: socket.id,
      userName: obj.name,
    };
    // 暂存socket.name 为user.userId;在用户退出时候将会用到
    socket.name = user.userId;
    /*不存在则增加 */
    if (!onLineUsers.hasOwnProperty(user.userId)) {
      //不存在则增加
      onLineUsers[user.userId] = {};
      onLineUsers[user.userId]["username"] = user.userName;
      onLineUsers[user.userId]["isJoinRoom"] = false;
      onLineCounts++;

      /*一个用户新增加，向全部client监听login的socket的实例发送响应，响应内容为一个对象*/
      Object.keys(onLineUsers).forEach((e) => {
        var curSocket = io.to(e);
        curSocket.emit("login", {
          onLineUsers: onLineUsers,
          onLineCounts: onLineCounts,
          user: {
            userId: e,
            userName: onLineUsers[e]["username"],
          },
          msg: 200,
        });
      });
    } else {
      Object.keys(onLineUsers).forEach((e) => {
        var curSocket = io.to(e);
        curSocket.emit("login", {
          onLineUsers: onLineUsers,
          onLineCounts: onLineCounts,
          user: {
            userId: e,
            userName: onLineUsers[e]["username"],
          },
          msg: 500,
        });
      });
    }

    console.log("[ 用户在线 ]", socket.id); //在server控制台中打印某某某用户增加到了棋牌室
  });
  socket.on("match", (data) => {
    console.log("[ 开始匹配 ]", data.id);
    var curSocket = io.to(data.id);
    // 匹配
    var strMatchMsg = "正在为您匹配对手，请稍后";
    curSocket.emit("match", {
      msg: strMatchMsg,
      id: data.id,
    });
    // 过滤掉本人
    var objUser = Object.keys(onLineUsers).filter(function (item) {
      return item != data.id;
    });
    onLineUsers[data.id]["isJoinRoom"] = true;
    // 创建房间
    for (let j = 0; j < objUser.length; j++) {
      if (onLineUsers[objUser[j]]["isJoinRoom"] == true) {
        onRooms[data.id + objUser[j]] = {}
        onRooms[data.id + objUser[j]]["id1"] = data.id
        onRooms[data.id + objUser[j]]["id2"] = objUser[j]
        onLineUsers[data.id]["isJoinRoom"] = false;
        onLineUsers[objUser[j]]["isJoinRoom"] = false;
        break;
      } else {
        continue;
      }
    }
    data.timeout = setTimeout(() => {
      curSocket.emit("match", {
        msg: strMsg + "匹配超时",
        error: true,
        id: data.id,
      });

      onLineUsers[data.id]["isJoinRoom"] = false;


    }, 10000);

    data.interval = setInterval(() => {
      Object.keys(onRooms).forEach(e => {
        if (e.search(data.id) != -1) {
          clearTimeout(data.timeout);
          curSocket.emit("match", {
            msg: strMsg + "匹配成功,您的对手:" + onLineUsers[onRooms[e]["id2"]]['username'],
            success: true,
            id: data.id,
            name: onLineUsers[onRooms[e]["id1"]]['username'],
            user1: {
              info: onLineUsers[onRooms[e]["id1"]],
              camp: "CHU"
            },
            user2: {
              info: onLineUsers[onRooms[e]["id2"]],
              camp: "HAN"
            }
          });
          clearInterval(data.interval);
        }
      })
    }, 1000);
  });
  socket.on("play", (data) => {
    // 下棋
    var curSocket = null
    Object.keys(onRooms).forEach(e => {
      if (e.search(data.id) != -1) {
        curSocket = io.to(onRooms[e]["id1"]).to(onRooms[e]["id2"]);
        curSocket.emit("play", data)
      }
    })


  });
  socket.on("win", function (obj) {
    // 胜利方
  });
  socket.on("turn", function (obj) {
    // 下棋方
  });

  socket.on("disconnect", () => {
    // console.log("user disconnected");
  });
});
